package com.bjqh.edu.UI.Activity.Login;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bjqh.edu.Base.AppConstants;
import com.bjqh.edu.Base.EasyActivity;
import com.bjqh.edu.Bean.Code;
import com.bjqh.edu.Bean.Login;
import com.bjqh.edu.R;
import com.bjqh.edu.UI.Activity.Index.FreeReservationActivity;
import com.bjqh.edu.UI.dialog.LoadDialog;
import com.bjqh.edu.Widget.CountDownTimerUtils;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpParams;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

public class RegisterActivity extends EasyActivity {

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.rl_top_tilte)
    RelativeLayout rlTopTilte;
    @BindView(R.id.et_Phone)
    EditText etPhone;
    @BindView(R.id.et_phone_verification)
    EditText etPhoneVerification;
    @BindView(R.id.get_iden_card)
    Button getIdenCard;
    @BindView(R.id.et_password)
    EditText etPassword;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.tv_send)
    Button tvSend;
    @BindView(R.id.et_password2)
    EditText etPassword2;
    @BindView(R.id.tv_qx)
    TextView tvQx;
    @BindView(R.id.rg)
    RadioGroup rg;
    @BindView(R.id.stu)
    RadioButton stu;
    @BindView(R.id.tea)
    RadioButton tea;
    @BindView(R.id.sz)
    TextView sz;
    @BindView(R.id.checkbox)
    CheckBox checkbox;
    private int numcode;
    String card;
    private LoadDialog dialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //全屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_register);
        ButterKnife.bind(this);
        initViews();
        initData();
        initEvents();
    }

    @Override
    protected void initViews() {
        tvTitle.setText("注册");
        dialog = new LoadDialog(this,"正在注册");


    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initEvents() {

        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        tvSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(etPhone.getText())) {
                    Toast.makeText(getApplicationContext(), "报告小主，手机号还没有填呢~~", Toast.LENGTH_SHORT).show();
                    // etPhone.setError("请填写手机号");
                    etPhone.requestFocus();
                    return;

                }
                if (TextUtils.isEmpty(etPhoneVerification.getText())) {
                    Toast.makeText(getApplicationContext(), "报告小主，验证码还没有填呢~~", Toast.LENGTH_SHORT).show();
                    etPhoneVerification.requestFocus();
                    return;

                }
                if (TextUtils.isEmpty(etPassword.getText())) {
                    Toast.makeText(getApplicationContext(), "报告小主，密码还没有填呢~~", Toast.LENGTH_SHORT).show();
                    etPassword.requestFocus();
                    return;

                }
                if (TextUtils.isEmpty(etName.getText())) {

                    Toast.makeText(getApplicationContext(), "报告小主，姓名还没有填呢~~", Toast.LENGTH_SHORT).show();
                    etName.requestFocus();
                    return;

                }

           /*       if (card!=null&&!card.equals(etPhoneVerification.getText().toString())) {
                      Toast.makeText(getApplicationContext(), "您输入的验证码有误，请重新获取", Toast.LENGTH_SHORT).show();
                      return;
                  }
*/
                if (!etPassword.getText().toString().equals(etPassword2.getText().toString())) {
                    Toast.makeText(getApplicationContext(), "报告小主，您输入的两次密码不一致哦~~", Toast.LENGTH_SHORT).show();

                    return;
                }
                if(!checkbox.isChecked())
                {
                    Toast.makeText(getApplicationContext(), "报告小主，您还没有阅读守则条例哦~~", Toast.LENGTH_SHORT).show();
                return;
                }

                HttpParams params = AppConstants.initPram();
                params.put("passWord", AppConstants.md5(etPassword.getText().toString()));
                params.put("name", etName.getText().toString());
                if (stu.isChecked()) {
                    params.put("role", "0");
                } else if (tea.isChecked()) {
                    params.put("role", "1");

                }
                params.put("mobile", etPhone.getText().toString());
                dialog.initDialog(RegisterActivity.this,"正在注册");
                OkGo.post(AppConstants.BASE_URL + "/user/add.shtml")
                        .tag(this)
                        .cacheKey("cacheKey")
                        .cacheMode(CacheMode.DEFAULT)
                        .params(params)
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(String s, Call call, Response response) {
                                Gson gson = new Gson();
                                Login login = gson.fromJson(s, Login.class);

                                if (login.getMsg().equals("注册成功")) {
                                    Toast.makeText(RegisterActivity.this, "报告小主，注册成功了哦", Toast.LENGTH_SHORT).show();
                                    finish();
                                    LoadDialog.closeDialog();

                                } else {
                                    Toast.makeText(RegisterActivity.this, "报告小主，您的手机号已注册哦~~", Toast.LENGTH_SHORT).show();
                                    LoadDialog.closeDialog();

                                }


                            }

                            @Override
                            public void onError(Call call, Response response, Exception e) {
                                Toast.makeText(RegisterActivity.this, "报告小主，服务器被外星人偷走啦~~", Toast.LENGTH_SHORT).show();
                                LoadDialog.closeDialog();
                            }
                        })

                ;
            }
        });
        sz.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.putExtra("url", AppConstants.H5_URL+"agree.html");
                intent.setClass(RegisterActivity.this, FreeReservationActivity.class);
                RegisterActivity.this.startActivity(intent);
            }
        });
        getIdenCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (TextUtils.isEmpty(etPhone.getText().toString())) {
                    Toast.makeText(RegisterActivity.this, "报告小主，先要填写手机号哦~~", Toast.LENGTH_SHORT).show();
                    etPhone.requestFocus();
                    return;
                }

                OkGo.post(AppConstants.BASE_URL + "/sys/shorMessage.shtml")
                        .tag(this)
                        .cacheKey("cacheKey")
                        .cacheMode(CacheMode.DEFAULT)
                        .params("mobile", etPhone.getText().toString())
                        // .params("type","注册")

                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(String s, Call call, Response response) {
                                Gson gson = new Gson();
                                Code code = gson.fromJson(s, Code.class);
                                if (code.getMsg().equals("OK")) {
                                    final CountDownTimerUtils mCountDownTimerUtils = new CountDownTimerUtils(getIdenCard, 60000, 1000); //倒计时1分钟
                                    mCountDownTimerUtils.start();
                                    Toast.makeText(RegisterActivity.this, "小主,验证码已发送到您的手机", Toast.LENGTH_SHORT).show();
                                    numcode = (int) ((Math.random() * 9 + 1) * 100000);
                                    Log.e("验证码请求成功", s);

                                    card = code.getCode();
                                } else {
                                    Toast.makeText(RegisterActivity.this, "报告小主，我在地球上没有找到您的手机号，您是不是输错了？", Toast.LENGTH_SHORT).show();
                                    Log.e("手机号已存在", s);

                                }


                            }

                            @Override
                            public void onError(Call call, Response response, Exception e) {
                                Toast.makeText(RegisterActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
                            }
                        })

                ;

            }
        });
    }



    /**
     * 验证手机格式
     */
    public static boolean isMobileNO(String mobiles) {
    /*
    移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
    联通：130、131、132、152、155、156、185、186
    电信：133、153、180、189、（1349卫通）
    总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
    */
        String telRegex = "[1][358]\\d{9}";//"[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(mobiles)) return false;
        else return mobiles.matches(telRegex);
    }
}
